package org.spring.springboot.service;

import org.spring.springboot.util.SpringContextUtils;
import org.spring.springboot.entity.Schedule;
import org.spring.springboot.entity.SchedulingRunnable;
import org.spring.springboot.mapper.ScheduleMapper;
import org.spring.springboot.mapper.ScheduleInstanceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RefreshTaskService {

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    @Autowired
    private ScheduleMapper jobMapper;

    @Scheduled(fixedRate = 5000,initialDelay = 3000) // 每5秒执行一次
    public void scheduledTask() {
        // Step1：获取目前进程中的定时任务清单
        int maxJobId = cronTaskRegistrar.getMaxJobId();

        // Step2：获取更新的定时任务清单
        List<Schedule> operateJobs = jobMapper.selectOperationJobs(maxJobId);
        ScheduleInstanceMapper scheduleInstanceMapper = SpringContextUtils.getBean(ScheduleInstanceMapper.class);
        // Step3：对于新增的定时任务进行新增，对于更新的定时任务进行修改,对于删除的定时任务进行删除
        for (Schedule setting : operateJobs) {
            SchedulingRunnable task = new SchedulingRunnable(setting.getBeanName()
                    , setting.getMethodName()
                    , setting.getCronKey()
                    , setting.getJobId());
            task.setMapper(scheduleInstanceMapper);
            switch (setting.getOperation()) {
                case "ADD":
                    cronTaskRegistrar.addCronTask(task, setting.getCronExpression());
                    break;
                case "MODIFY":
                    cronTaskRegistrar.removeCronTask(task);
                    cronTaskRegistrar.addCronTask(task, setting.getCronExpression());
                    break;
                case "REMOVE":
                    cronTaskRegistrar.removeCronTask(task);
                    break;
                default:
                    System.out.println(1);
            }
        }
    }
}
